<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="4">
          <el-input
            v-model="queryParams.wCode"
            placeholder="请输入仓库编码"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="4">
          <el-input
            v-model="queryParams.wName"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wm:warehouse:manage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wm:warehouse:manage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wm:warehouse:manage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wm:warehouse:manage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="manageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="仓库名称" align="center" prop="wName" />
      <el-table-column label="仓库编码" align="center" prop="wCode" />
      <el-table-column label="面积" align="center" prop="wArea" />
      <el-table-column label="位置" align="center" prop="wPosition" />
      <el-table-column label="负责人" align="center" prop="wManager" />
      <el-table-column
        label="库区数量"
        align="center"
        prop="storageAreaCount"
      />
      <el-table-column label="备注" align="center" prop="wDesc" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-detail"
            @click="handleDetails(scope.row)"
            v-has-permi="['wm:warehouse:manage:query']"
            >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wm:warehouse:manage:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wm:warehouse:manage:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库名称" prop="wName">
          <el-input v-model="form.wName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="面积" prop="wArea">
          <el-input v-model="form.wArea" placeholder="请输入面积" />
        </el-form-item>
        <el-form-item label="负责人" prop="wManager">
          <el-input v-model="form.wManager" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="位置" prop="wPosition">
          <el-input v-model="form.wPosition" placeholder="请输入位置" />
        </el-form-item>
        <el-form-item label="备注" prop="wDesc">
          <el-input
            v-model="form.wDesc"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listManage, getManage, delManage, addManage, updateManage } from "@/api/yyj/wm/warehouse/manage";

export default {
  name: 'Manage',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      saCounts: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库表格数据
      manageList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wCode: null,
        wName: null,
        wArea: null,
        wManager: null,
        wPosition: null,
        wDesc: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        wCode: [
          { required: true, message: '仓库编码不能为空', trigger: 'blur' },
        ],
        wName: [
          { required: true, message: '仓库名称不能为空', trigger: 'blur' },
        ],
        wArea: [
          { required: true, message: '面积不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const regex = /^\d+(\.\d{1,2})?$/;
              if (!regex.test(value)) {
                callback(new Error('面积必须是数字，并且最多保留两位小数'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        wManager: [
          { required: true, message: '负责人不能为空', trigger: 'blur' },
        ],
        wPosition: [
          { required: true, message: '位置不能为空', trigger: 'blur' },
        ],
        wDesc: [
          { required: false, message: '备注不能为空', trigger: 'blur' }
        ],
        createBy: [
          { required: true, message: '创建人不能为空', trigger: 'blur' },
        ],
        createTime: [
          { required: true, message: '创建时间不能为空', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询仓库列表 */
    getList() {
      this.loading = true
      listManage(this.queryParams).then(response => {
        this.manageList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        wCode: null,
        wName: null,
        wArea: null,
        wManager: null,
        wPosition: null,
        wDesc: "",
        createBy: null,
        createTime: null,
        updateBy: this.$store.state.user.name,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 查询参数重置
    resetQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        wCode: null,
        wName: null,
        wArea: null,
        wManager: null,
        wPosition: null,
        wDesc: null,
      };
      this.resetForm("queryForm")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetQueryParams();
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.wCode)
      this.saCounts = selection.map(item => item.storageAreaCount)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加仓库'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const wCode = row.wCode || this.ids
      getManage(wCode).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改仓库'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let name = this.$store.state.user.name
          if (this.form.wCode != null) {
            this.form.updateBy = name
            updateManage(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            this.form.updateBy = name
            this.form.createBy = name
            addManage(this.form).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const wCodes = row.wCode || this.ids;
      let saCount = row.storageAreaCount || this.saCounts
      this.$modal.confirm('是否确认删除仓库编号为"' + wCodes + '"的数据项？').then(() => {
        if (Array.isArray(saCount)) {
          if (saCount.some(count => count > 0)) {
            this.$modal.msgWarning("请先删除当前仓库的库区")
            return Promise.reject("Storage area count is greater than 0");
          }
        } else if (saCount > 0) {
          this.$modal.msgWarning("请先删除当前仓库的库区")
          return Promise.reject("Storage area count is greater than 0");
        }
        return delManage(wCodes, saCount);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        '/yyj/wm/warehouse/manage/export',
        {
          ...this.queryParams,
        },
        `manage_${new Date().getTime()}.xlsx`
      )
    },
    /** 详情按钮操作 */
    handleDetails(row) {
      const wCode = row.wCode || this.ids
      this.$router.push({
        path:'/warehouse/details',
        query: {
          wCode: wCode
        }
      })
    },
  },
}
</script>
